package com.loongtech.bi.action;

import com.loongtech.bi.action.admin.LoginAction;
import com.loongtech.bi.entity.system.EntitySysUser;
import com.loongtech.bi.manager.system.BiPlatformManager;
import com.loongtech.bi.manager.system.ConfigManager;
import com.loongtech.bi.manager.system.SysUserManager;
import com.loongtech.bi.support.Session;
import com.loongtech.core.util.Time;
import com.loongtech.core.util.Utils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.Serializable;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@Scope("view")
public class PageHelper implements Serializable{
	private static final long serialVersionUID = 1L;
	private static DecimalFormat PERCENT_DF = new DecimalFormat("0.00%");

    @Autowired
    private Session session;
    @Autowired
    private SysUserManager sysUserManager;

    @Autowired
    private HttpServletRequest request;

    @SuppressWarnings({ "serial" })
    public Map<String, String> tooltip  = new HashMap<String, String>(){
        {
            put("激活设备", "安装并首次启动游戏的设备数");
            put("新增账号数", "首次登陆游戏的账号（游戏服务器新建账号算作游戏的一个新增用户）");
            put("活跃账号数", "统计周期内登陆过游戏的去重账号数");
            put("付费账号数", "游戏中付费金额大于0的去重账号数");
            put("付费金额", "统计周期内账号在游戏中的付费总额");
            put("活跃付费率", "付费账号数/活跃账号数");
            put("付费ARPU", "付费金额/付费账号数");
            put("活跃ARPU", "付费金额/活跃账号数据");
            put("昨日新增账号次留", "昨日新增且今日活跃账号数/昨日新增账号数");
            put("前日新增账号三留", "前日新增且今日活跃账号数/前日新增账号数");
            put("在线人数", "服务器同时在线人数（计算逻辑：每五分钟更新一次，服务器在线的不重复账号数）");
            put("PCU", "Peak concurrent users，最高同时在线用户数（计算逻辑：统计周期内同时在线账号数的最大值）");
            put("ACU", "Average concurrent users，平均同时在线用户数（计算逻辑：统计周期内同时在线账号数的平均值）");
            put("服务器容量", "服务器最大容纳同时在线人数");
            put("实时使用率", "实时在线人数/服务器容量");
            put("昨日最高使用率", "昨日PCU/服务器容量");
            put("次日留存率", "新用户在第2日（含新增当日）登录游戏账号数/统计周期内总新增账号数");
            put("3日留存率", "新用户在第3日（含新增当日）登录游戏账号数/统计周期内总新增账号数");
            put("7日留存率", "新用户在第7日（含新增当日）登录游戏账号数/统计周期内总新增账号数");
        }
    };

    public String getToolTip(String t) {
        if (StringUtils.isEmpty(t)) {
            return t;
        }
        String result = tooltip.get(t);
        if (result != null) {
            return result;
        } else {
            String t1 = t.substring(0, t.length() - 3);
            result = tooltip.get(t1);
            return result == null ? t : result;
        }
    }

    private String project;
    public Map<String, String> projects = LoginAction.projects;

    public void updateProject() {
        if ("bi".equals(project)) {
             return;
        }

        try {
            if (project.endsWith("/")) {
                project = project.substring(0, project.length() - 1);
            }
           /* HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
            response.sendRedirect(project + "/resources/pages/main.jsf?faces-redirect=true&username=" + session.getUserName());
*/

            EntitySysUser user = sysUserManager.getUserByName(session.getUserName());
            if (user != null) {
                FacesContext.getCurrentInstance().getExternalContext().redirect(project + "/resources/pages/main.jsf?faces-redirect=true&uname=" + session.getUserName() + "&sign=" + user.getPassword());
                FacesContext.getCurrentInstance().responseComplete();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return;
    }

    public static int double2Int(double num) {
        return (int)Math.round(num);
    }

	/**
	 * 将小数的百分比转化为百分比字符串，0.222222-->22.22%
	 * @param
	 * @return
	 * @author HivenYang
	 *	@date 2015年2月6日
	 */
	public static String double2Percent(Double d) {
		d = NumberUtils.isNumber(d.toString()) ? d : 0;
		if (d == 0) {
			return "";
		}
		
		return PERCENT_DF.format(d);
	}
	
	//保留两位小数
	public static Float floatKeepTwoNumber(Float f) {
		DecimalFormat df = new DecimalFormat("0.00");
		BigDecimal bigDecimal = new BigDecimal(df.format(f));
		
		return bigDecimal.floatValue();
	}

    public static String formatInt(String data) {
        DecimalFormat df = new DecimalFormat("#,###");
        return df.format(Integer.parseInt(data));
    }

    public static void main(String[] args) {
        System.out.println(formatFloat("0.98"));
    }


    public static String formatFloat(String data) {
        DecimalFormat df = new DecimalFormat("#,###.00");
        String result = df.format(Float.parseFloat(data));
        return result.startsWith(".") ? ("0" + result) : result;
    }

	//保留一位小数
    public static Float floatKeepOneNumber(Double f) {
        DecimalFormat df = new DecimalFormat("0.0");
        BigDecimal bigDecimal = new BigDecimal(df.format(f));

        return bigDecimal.floatValue();
    }

    //保留两位小数
	public static Float floatKeepTwoNumber(Double f) {
		DecimalFormat df = new DecimalFormat("0.00");
		BigDecimal bigDecimal = new BigDecimal(df.format(f));
		
		return bigDecimal.floatValue();
	}
	
	//保留四位小数
	public static Float floatKeep4Number(Float f) {
		DecimalFormat df = new DecimalFormat("0.0000");
		BigDecimal bigDecimal = new BigDecimal(df.format(f));
		
		return bigDecimal.floatValue();
	}

	//保留四位小数
	public static Double floatKeep4Number(Double d) {
		DecimalFormat df = new DecimalFormat("0.0000");
		BigDecimal bigDecimal = new BigDecimal(df.format(d));
		
		return bigDecimal.doubleValue();
	}
	
	public static String formatDate(Date date) {
		if (date == null) {
			return "";
		}
		
		SimpleDateFormat format = new SimpleDateFormat("MM-dd");
		return format.format(date.getTime());
	}
	
	public static String getDateStr(long date) {
		return Time.formatTime(date, Time.TIMEPATTERN_ALL3);
	}
	
	public String formatMenuitemValue(String value) {
		return "&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;" + value;
	}
	
	public String getPlatformNameById(String platformId) {
		return BiPlatformManager.getPlatformNameById(platformId);
	}
	
	public String getChannelNameById(String channelId) {
		return BiPlatformManager.getChannelNameById(channelId);
	}
	
	public String getServerNameById(String serverId) {
		return BiPlatformManager.getServerNameById(serverId);
	}
	
	public String getLostLastTime() {
		return Time.getDateStr(new Date(System.currentTimeMillis() - 7 * Time.DAY));
	}
	
	// 秒to分
	public int getM(int s) {
		return s / 60; 
	}
	
	public static String getNewDateDetailStr() {
		return Time.getNewDateDetailStr();
	}
	
	@Autowired
	private ConfigManager configManager;

	public String getMoneyType() {
		return configManager.getConfigValueByName(ConfigManager.MONEY_TYPE) == null ? "($)" : configManager.getConfigValueByName(ConfigManager.MONEY_TYPE);
	}
	
	public String getGameName() {
		return configManager.getConfigValueByName(ConfigManager.GAME_NAME) == null ? "" : configManager.getConfigValueByName(ConfigManager.GAME_NAME);
	}

    public String getGameRechargeFlowName() {
        return configManager.getConfigValueByName(ConfigManager.GAME_RECHARGE_FLOW_NAME) == null ? "元宝" : configManager.getConfigValueByName(ConfigManager.GAME_RECHARGE_FLOW_NAME);
    }

    public String getMainPage() {
       /* List<EntitySysUserRole> userRoles = sysUserRoleManager.findByQuery("from EntitySysUserRole where 1 = 1 and userid = :userid", "userid", session.getUserId());
        if (userRoles != null && userRoles.size() > 0 && userRoles.get(0) != null) {
            EntitySysRole role = sysRoleManager.get(userRoles.get(0).getRoleId());
            if (role != null && "boss".equals(role.getName())) {
                return "realTime/bossRealTime.jsf";
            }
        }*/

        HttpSession session = request.getSession();
        String lastURL = (String) session.getAttribute("lastURL");

        return StringUtils.isEmpty(lastURL) ? "realTime/data1.jsf" : lastURL;
    }

    public String getProject() {
        return project;
    }

    public void setProject(String project) {
        this.project = project;
    }

    public Map<String, String> getProjects() {
        return projects;
    }

    public void setProjects(Map<String, String> projects) {
        this.projects = projects;
    }

    // 服务器是否分类
    public boolean isServerClass() {
        String c = configManager.getConfigValueByName(ConfigManager.SERVER_CLASS);
        return c != null && "1".equals(c) ? true : false;
    }

    public String md5(String s) {
        return Utils.md5(s);
    }


    // 今天是否比d2大dx天
    public boolean isBig(String d, int dx) {
	    return Time.getInterval(Time.formatDate(d, "yyyy-MM-dd"), Time.currentDate()) >= dx;
    }
}
